import useEaseInOut from '@/hooks/easeInOut'
import {long2Brief} from '@/libs/toolkit'
import {PropType, CSSProperties} from 'vue'
import {CnBoldSpan, CnMediumSpan, CnNormalSpan} from './text'

/**
 * @desc 数字滚动组件
 */
const RollerDigital = defineComponent({
  props: {
    bold: {
      type: Boolean,
      default: true
    },
    startVal: {
      type: Number,
      default: 0
    },
    endVal: {
      type: Number,
      default: 0
    },
    duration: {
      type: Number,
      default: 3000
    },
    autoplay: {
      type: Boolean,
      default: true
    },
    decimals: {
      type: Number,
      default: 0,
      validator: (v: number) => {
        return v >= 0
      }
    },
    isFormat: {
      type: Boolean,
      default: true
    },
    decimal: {
      type: String,
      default: '.'
    },
    separator: {
      type: String
    },
    prefix: {
      type: String,
      default: ''
    },
    suffix: {
      type: String,
      default: ''
    },
    useEasing: {
      type: Boolean,
      default: true
    },
    easingFn: {
      type: Function,
      default: (t: number, b: number, c: number, d: number) => {
        return (c * (-Math.pow(3, (-10 * t) / d) + 1) * 1024) / 1023 + b
      }
    },
    style: Object as PropType<CSSProperties>
  },
  setup(props, {emit}) {
    const {count, countStart} = useEaseInOut({
      startVal: 0,
      endVal: props.endVal,
      isFormat: props.isFormat,
      decimals: props.decimals,
      separator: props.separator,
      autoplay: props.autoplay
    })

    watch(
      () => props.endVal,
      n => {
        if (typeof n === 'number' && n === n) {
          countStart({
            startVal: 0,
            endVal: n
          })
        }
      }
    )

    return () =>
      props.bold ? (
        <CnBoldSpan style={Object.assign({}, props.style)}>{props.endVal}</CnBoldSpan>
      ) : (
        <CnNormalSpan style={Object.assign({}, props.style)}>{props.endVal}</CnNormalSpan>
      )
  }
})

export default RollerDigital
